package com.resou.reader.search;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.resou.reader.R;
import com.resou.reader.api.entry.SearchBean;
import com.resou.reader.bookshelf.readhistory.datasupport.SearchHistory;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.bookshelf.listener.OnItemClickListener;
import com.resou.reader.search.adpter.SearchResultAdapter;
import com.resou.reader.search.adpter.SearchBeforeAdapter;
import com.umeng.analytics.MobclickAgent;

import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity<SearchPresenter> implements ISearchView, OnItemClickListener, View.OnClickListener {

    @BindView(R.id.search_edit)
    EditText mInputText;
    @BindView(R.id.search_recycler)
    RecyclerView mSearchRecycler;
    @BindView(R.id.no_search_result_layout)
    View noSearchView;
    @BindView(R.id.search_before_recycler)
    RecyclerView mSearchBeforeRecycler;
    private SearchBeforeAdapter mBeforeAdapter;
    boolean isLoadingMore = false;

    public static void start(Context context) {
        Intent starter = new Intent(context, SearchActivity.class);
//        starter.putExtra();
        context.startActivity(starter);
    }

    private SearchResultAdapter mAdapter ;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    private static final String TAG = "SearchActivity-App";

    @Override
    protected void initView() {
        //设置输入框的监听器，监听用户按下搜索键
        mInputText.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                // 先隐藏键盘
                ((InputMethodManager) Objects.requireNonNull(getSystemService(INPUT_METHOD_SERVICE)))
                        .hideSoftInputFromWindow(Objects.requireNonNull(SearchActivity.this.getCurrentFocus())
                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                presenter.search(mInputText.getText().toString());
            }
            return false;
        });

        mAdapter = new SearchResultAdapter(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mSearchRecycler.setLayoutManager(layoutManager);
        mSearchRecycler.setAdapter(mAdapter);
//        mSearchRecycler.setHasFixedSize(true);
        mSearchRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
//                int totalItemCount = layoutManager.getItemCount();
                int totalItemCount = mAdapter.getItemCount();
                if (lastVisibleItem >= totalItemCount - 2 && dy > 0) {  //还剩2个Item时加载更多
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        presenter.searchNext(mInputText.getText().toString());
                    }
                }
            }
        });
        mBeforeAdapter = new SearchBeforeAdapter(this);
        mBeforeAdapter.setInteractionListener(new SearchBeforeAdapter.SearchBeforeInteractionListener() {
            @Override
            public void onChangeClicked() {
                presenter.getHotPush();
            }

            @Override
            public void onDeleteClicked() {
                presenter.deleteAllHistory();
                presenter.getAllHistory();
            }
        });
        //搜索记录
        mSearchBeforeRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mSearchBeforeRecycler.setAdapter(mBeforeAdapter);

        mInputText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

//                if (PageUtils.isEmpty(s.toString())) {
//                    mSearchBeforeRecycler.setVisibility(View.VISIBLE);
//                    mSearchRecycler.setVisibility(View.GONE);
//                    noSearchView.setVisibility(View.GONE);
//                    //刷新搜索记录
//                    presenter.getAllHistory();
//                }
                mInputText.requestFocus();
            }
        });
    }

    @Override
    protected void retryRefreshData() {

    }

    @Override
    protected void initPresenter() {
        presenter = new SearchPresenter(this);
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @OnClick({R.id.clear_image, R.id.search_cancel})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_image:
                //清空输入框
                mInputText.setText("");
                showHotAndHistory();
                break;
            case R.id.search_cancel:
                finish();
                break;
            case R.id.hot_text:
                String str = ((TextView) v).getText().toString();
                mInputText.setText(str);
                presenter.search(str);
                mInputText.setSelection(str.length());//移动光标到最后
                MobclickAgent.onEvent(this, "search", str);
                break;
            case R.id.history_item_group://点了搜索历史
                String text = (String) v.getTag();
                mInputText.setText(text);
                presenter.search(text);
                mInputText.setSelection(text.length());//移动光标到最后
                break;
            case R.id.right_text:
                //换一换
                break;
        }
    }

    @Override
    public void showSearchResult(List<SearchBean> list, String source) {
        mSearchBeforeRecycler.setVisibility(View.GONE);
        if (list != null && list.size() == 0) {
            noSearchView.setVisibility(View.VISIBLE);
            mSearchRecycler.setVisibility(View.GONE);
        } else {
            noSearchView.setVisibility(View.GONE);
            mSearchRecycler.setVisibility(View.VISIBLE);
        }
        mAdapter.setList(list, source);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showHot(List<String> hots) {
        mBeforeAdapter.setHotList(hots);
    }

    @Override
    public void showHistory(List<SearchHistory> history) {
        mBeforeAdapter.setHistoryList(history);
    }

    @Override
    public void showHotAndHistory() {
//        presenter.getHotPush();
        presenter.getAllHistory();
        mSearchBeforeRecycler.setVisibility(View.VISIBLE);
        noSearchView.setVisibility(View.GONE);
        mSearchRecycler.setVisibility(View.GONE);
    }

    @Override
    public void addSearchResult(List<SearchBean> list, String source) {
        mAdapter.addList(list, source);
        isLoadingMore = false;
    }

    @Override
    public void onItemClicked(RecyclerView.Adapter adapter, View itemView, int index) {

    }
}
